package com.lantosec.hmrp.modules.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.kit.Result;
import com.lantosec.hmrp.core.kit.tree.TreeNodeVo;
import com.lantosec.hmrp.core.shiro.TokenUtil;
import com.lantosec.hmrp.modules.system.entity.SysDeptUser;
import com.lantosec.hmrp.modules.system.entity.SysMenu;
import com.lantosec.hmrp.modules.system.mapper.SysMenuMapper;
import com.lantosec.hmrp.modules.system.service.ISysDeptService;
import com.lantosec.hmrp.modules.system.service.ISysMenuService;
import com.lantosec.hmrp.modules.system.vo.SysMenusVO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 系统菜单表 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-02-12
 */
@Service
@Primary
@Log4j2
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
    @Autowired
    private ISysDeptService iSysDeptService;

    /**
     * 菜单排序
     *
     * @param id
     * @param menuOrder
     */
    @Override
    public void updateOrder(String id, Integer menuOrder){
        SysMenu sysMenu = new SysMenu();
        sysMenu.setMenuOrder(menuOrder);
        baseMapper.update(sysMenu,new QueryWrapper<SysMenu>()
                .eq(SysMenu.ColName.menu_id.toString(),id));
    }

    @Override
    public List<TreeNodeVo> menuTree() {
        return menuTree(null);
    }

    /**
     * 根据指定ID查询对应的菜单树
     *
     * @param menuId 菜单ID
     * @return 菜单树
     */
    @Override
    public List<TreeNodeVo> menuTree(String menuId) {
        List<TreeNodeVo> list = menuNodes(menuId);
        List tree = new ArrayList<TreeNodeVo>();
        if (list != null && list.size() > 0) {
            list.forEach(node -> {
                if (!node.isLeaf()) {
                    List<TreeNodeVo> children = menuTree(node.getKey());
                    node.setChildren(children);
                }
                tree.add(node);
            });
        }
        return tree;
    }

    /**
     * 获得指定Id下的菜单树节点，不包含节点下的子节点
     *
     * @param menuId 菜单ID
     * @return 节点列表
     */
    @Override
    public List<TreeNodeVo> menuNodes(String menuId) {
        List<SysMenu> list = getMenuById(menuId);
        if (list != null && list.size() > 0) {
            List<TreeNodeVo> nodes = new ArrayList<TreeNodeVo>();
            list.forEach(menu -> {
                nodes.add(new TreeNodeVo(menu.getMenuId(), menu.getShowName(),menu.getUrl()));
            });
            return nodes;
        }
        return new ArrayList<TreeNodeVo>();
    }

    /**
     * 查询父类菜单为ID下的子菜单
     * @param id
     * @return
     */
    public List<SysMenu> getMenuById(String id) {
        if(StringUtils.isNotEmpty(id)){
            return this.list(new QueryWrapper<SysMenu>()
                    .eq(SysMenu.ColName.parent_id.toString(), id)
                    .orderByAsc(SysMenu.ColName.menu_order.toString(), SysMenu.ColName.menu_id.name()));
        }else {
            return this.list(new QueryWrapper<SysMenu>().isNull(SysMenu.ColName.parent_id.toString())
                    .orderByAsc(SysMenu.ColName.menu_order.toString(), SysMenu.ColName.menu_id.name()));
        }
    }

    /**
     * 查询当前菜单下的子菜单
     *
     * @param id
     * @return
     */
    @Override
    public List<SysMenu> getMenuPage(String id) {
        if(StringUtils.isNotEmpty(id)){
            return this.list(new QueryWrapper<SysMenu>().eq(SysMenu.ColName.parent_id.toString(),id).orderByAsc(SysMenu.ColName.menu_order.toString()));
        }else{
            return this.list(new QueryWrapper<SysMenu>().isNull(SysMenu.ColName.parent_id.toString()).orderByAsc(SysMenu.ColName.menu_order.toString()));
        }
    }

    @Override
    public String queryMaxmenuId(String parentId) {
        String menuId = null;
        if(StringUtils.isNotEmpty(parentId)){
            menuId = baseMapper.queryMaxmenuIdByParentId(parentId);
            return StringUtils.isEmpty(menuId) ? parentId+"001" :menuId;
        }else{
            menuId = baseMapper.queryMaxmenuId(parentId);
            return StringUtils.isEmpty(menuId) ? "001":menuId;
        }
    }

    @Override
    public List<SysMenusVO> getAll(String menuId,String deptId,String positionId) {
        List<SysMenusVO> sysMenuVOListList = null;
        //获取当前用户id和名称
        String userId = TokenUtil.getUserId();
        //如果是第一次登录，默认选择是主部门
        if(StringUtils.isEmpty(deptId) || StringUtils.isEmpty(positionId)){
            //查询当前用户的主部门和岗位
            SysDeptUser sysDeptUser = iSysDeptService.getDeptByUserId(userId);
            if(null != sysDeptUser){
                deptId = sysDeptUser.getDeptId();
                positionId = sysDeptUser.getPositionId();
            }
        }
        sysMenuVOListList = getSysMenusVOS(menuId, userId,deptId,positionId);
        return sysMenuVOListList;
    }

    @Override
    public List<SysMenusVO> getAllMenu(String menuId) {
        List<SysMenusVO> sysMenuVOListList = new ArrayList<>();
        if(StringUtils.isNotEmpty(menuId)){
            sysMenuVOListList = baseMapper.getSysMenus(menuId);
        }else {
            sysMenuVOListList = baseMapper.getSysMenus(null);
        }
        sysMenuVOListList.forEach(param->{
            List<SysMenusVO> sysMenuVOs = getAllMenu(param.getMenuId());
            param.setChildren(sysMenuVOs);
        });
        return sysMenuVOListList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMenuInfo(String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            //删除菜单表数据sys_menu
            this.removeByIds(Arrays.asList(ids.split(",")));
            //删除角色菜单挂接表 sys_role_menu
            baseMapper.deleteRoleMenu(ids);
        }
    }

    private List<SysMenusVO> getSysMenusVOS(String menuId, String userId,String deptId,String positionId) {
        //查询当前用户的菜单
        List<SysMenusVO> sysMenuVOListList = new ArrayList<>();
        if(StringUtils.isNotEmpty(menuId)){
            sysMenuVOListList = baseMapper.getSysMenusVO(menuId,userId,deptId,positionId);
        }else {
            sysMenuVOListList = baseMapper.getSysMenusVO(null,userId,deptId,positionId);
        }
        sysMenuVOListList.forEach(param->{
            List<SysMenusVO> sysMenuVOs = getSysMenusVOS(param.getMenuId(),userId,deptId,positionId);
            param.setChildren(sysMenuVOs);
        });
        return sysMenuVOListList;
    }
}
